package pers.lan.print;

import javax.print.*;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.Sides;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Map;

/**
 * @author <a href="mailto:1728209643@qq.com">lan</a>
 * @class pers.lan.print.Printer
 * @date 2019-04-11 13:52
 */
public class Printer {

    public static void print(String printFilePath, Map<Object, Object> map) {

        try {
            // 构建打印请求属性集
            PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
            // 设置打印格式，因为未确定文件类型，这里选择AUTOSENSE
            DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
            // 查找所有的可用打印服务
            // [发送至 OneNote 2013, NPI82AACC (HP LaserJet M1536dnf MFP), Microsoft XPS Document Writer, Fax, CutePDF Writer]
            // 定位默认的打印服务
            PrintService defaultService = PrintServiceLookup.lookupPrintServices(flavor, pras)[0];

            if (defaultService != null) {

                //A4纸张
                //pras.add(MediaSize.A4);

                // 创建打印作业
                DocPrintJob job = defaultService.createPrintJob();
                // 构造待打印的文件流
                FileInputStream fis = new FileInputStream(printFilePath);
                DocAttributeSet das = new HashDocAttributeSet();
                // 建立打印文件格式
                Doc doc = new SimpleDoc(fis, flavor, das);
                // 打印份数
                if (map.get("Copies") != null) {
                    pras.add(new Copies((Integer) map.get("Copies")));
                } else {
                    pras.add(new Copies(1));
                }
                //双面打印
                if (map.get("duplex") != null) {
                    if ((Boolean) map.get("duplex")) {
                        pras.add(Sides.DUPLEX);
                    }
                } else {
                    pras.add(Sides.DUPLEX);
                }
                // 进行文件的打印
                job.print(doc, pras);
            }
        } catch (FileNotFoundException | PrintException e) {
            e.printStackTrace();
        }
    }
}
